package com.wawei.seeds.champion;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.wawei.seeds.R;
import com.wawei.seeds.model.HeroInfo;
import com.wawei.seeds.model.WalnutMainEvent;
import com.wawei.seeds.services.WalnutMainServiceHandler;
import com.wawei.seeds.utils.ImageLoader;
import com.wawei.seeds.utils.PrefUtils;
import com.wawei.seeds.utils.RetrofitNetworkService;
import com.wawei.seeds.utils.WalnutBaseNofityHandler;

import java.io.Serializable;

import butterknife.ButterKnife;
import butterknife.InjectView;
import retrofit.RestAdapter;

/**
 * Created by t27891 on 15/6/20.
 */
public class ChampionActivity extends ActionBarActivity {
    @InjectView(R.id.walnut_logo)ImageView logoImage;
    @InjectView(R.id.walnut_event_name)TextView eventName;
    @InjectView(R.id.walnut_event_image)ImageView eventImage;
    @InjectView(R.id.walnut_available_amount)TextView availableAmount;
    @InjectView(R.id.walnut_event_title)TextView eventTitle;
    @InjectView(R.id.walnut_event_action)TextView eventAction;

    @InjectView(R.id.walnut_event_detail)TextView eventDetail;
    @InjectView(R.id.walnut_event_value)TextView eventValue;
    @InjectView(R.id.walnut_hero_appointment)View appointmentView;
    @InjectView(R.id.submit_appointment)ImageView submitAppointmentImage;
    @InjectView(R.id.walnut_hero_appointment_status)TextView appointmentStatusView;

    @InjectView(R.id.walnut_hero_head)ImageView eventHeroHeadImage;
    @InjectView(R.id.walnut_hero_skill)TextView eventHeroSkill;
    @InjectView(R.id.walnut_hero_introduction)TextView eventHeroIntroduction;

    @InjectView(R.id.walnut_event_sharing)View eventSharing;

    private WalnutMainEvent event;
    private WalnutMainServiceHandler serviceHandler;
    private ImageLoader imageLoader;
    private HeroNotifyHandler notifyHandler;

    //For getting publisher's info async
    public static final int GET_HERO_INFO = 0x01;

    //For getting champion event info async
    public static final int GET_EVENT_INFO = 0x02;

    //For transferring the gotten item data. sometimes the item data has been downloaded before
    //opening ChampionActivity
    public static final String ITEM_DATA = "item";

    public static final String APPOINTMENT_STATUS_DONE = "已约";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_walnut_hero_detail);
        ButterKnife.inject(this);

        serviceHandler = new WalnutMainServiceHandler(this);
        imageLoader = new ImageLoader(this, R.drawable.event_placeholder);
        notifyHandler = new HeroNotifyHandler(this);

        Serializable serializable = getIntent().getSerializableExtra(ITEM_DATA);
        if(null == serializable){
            Toast.makeText(this, R.string.exception_no_data, Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
        else {
            event = (WalnutMainEvent)serializable;
            initChampionEvent(event.eventId, String.valueOf(PrefUtils.getUserId(this)));
            initHero(event.publisherId);
            init();
        }
    }

    private void initChampionEvent(String itemId, String loggedIn){
        RestAdapter restAdapter = RetrofitNetworkService.makeAsyncRestAdapter();
        serviceHandler.retrieveEventDetail(restAdapter, itemId, loggedIn,
                notifyHandler, GET_EVENT_INFO);
    }
    
    private void initHero(String heroId){
        RestAdapter restAdapter = RetrofitNetworkService.makeAsyncRestAdapter();
        serviceHandler.retrieveHeroDetail(restAdapter, heroId, notifyHandler, GET_HERO_INFO);
    }

    /**
     * Initialize the views
     * This activity is created by WalnutMainActivity, so the basic info of the event can be gotten from
     * the extra of intent. It has nice efficiency.
     */
    private void init(){
        appointmentView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                submitAppointment();
            }
        });
        logoImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
                finish();
            }
        });
        eventSharing.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ChampionActivity.this, ChampionMoreActivity.class);
                ChampionActivity.this.startActivity(intent);
            }
        });

        if(null != event) {
            initEvent();
        }

    }

    private void initEvent(){
        eventName.setText(event.publisher + " " + event.role);
        availableAmount.setText(event.available);
        eventTitle.setText(event.title);
        eventAction.setText(event.action);
        eventDetail.setText(event.detail);
        eventValue.setText(event.value);
        if(null == event.status || event.status.length() == 0){
            submitAppointmentImage.setImageResource(R.drawable.red_square);
            appointmentStatusView.setText(R.string.walnut_event_status_do);
        }
        else if(event.status.equals(APPOINTMENT_STATUS_DONE)){
            submitAppointmentImage.setImageResource(R.drawable.grey_square);
            appointmentStatusView.setText(R.string.walnut_event_status_done);
            appointmentView.setOnClickListener(null);
        }
        else {
            submitAppointmentImage.setImageResource(R.drawable.grey_square);
            appointmentStatusView.setText(R.string.walnut_event_status_waiting);
            appointmentView.setOnClickListener(null);
        }
        imageLoader.loadImage(event.AD, eventImage, false, false);
    }

    /**
     * Response to user's appointment
     */
    private void submitAppointment(){
        //TODO: submit a appointment with publisher
        Toast.makeText(ChampionActivity.this, "Want a appointment with publisher", Toast.LENGTH_SHORT).show();
    }

    private static class HeroNotifyHandler extends WalnutBaseNofityHandler<ChampionActivity, HeroInfo>{
        public HeroNotifyHandler(ChampionActivity championActivity) {
            super(championActivity);
        }

        @Override
        public void handleOtherMessage(Message msg) {
            Bundle bundle = msg.getData();
            if(msg.what == GET_HERO_INFO){
                HeroInfo info = (HeroInfo)bundle.get(RetrofitNetworkService.RESULT_DATA);
                get().imageLoader.loadImage(info.headPortrait, get().eventHeroHeadImage, true, false);

                StringBuilder sb = new StringBuilder();
                for(int i=0;i<info.skills.size();i++){
                    sb.append(info.skills.get(i));
                    sb.append("，");
                }
                sb.deleteCharAt(sb.length() - 1);
                get().eventHeroSkill.setText(sb.toString());

                get().eventHeroIntroduction.setText(info.brief);
            }
            else if(msg.what == GET_EVENT_INFO){
                get().event =
                        (WalnutMainEvent)bundle.get(RetrofitNetworkService.RESULT_DATA);
                get().initEvent();
            }
            super.handleOtherMessage(msg);
        }
    }
}
